import React, {Component} from 'react';
import {Button, Row, Col, Form, Input, Table, Modal, Select, Pagination} from 'antd';
import {EditCustomerPositions} from "../components/EditComponent";
import MapComponent from '../components/MapComponent';
import {customer, line} from "../value";
import app from '../AppMethod';
import {Consumer} from "../store";

const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;

class CustomerManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            data: [],
            pagination: {
                current: 0,
                total: 0,
                pagination: 0,
            },
            allPage: 0,
            searchData: {},
            editVisible: false,
            addConfirmLoading: false,
            locationData: {
                address: '广东省佛山市三水区xxxxxx',
                latitude: '23.3333334',//纬度
                longitude: '150.333335'//经度
            },
            routeItem: [],
            route_id: '',
            customer_sort: '',
            editCustomerId: '',
            validateStatus: '',
            helpStr: '',
        }
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };
    columns = [
        {
            title: '客户编号',
            dataIndex: 'customer_code'
        },
        {
            title: '客户名',
            dataIndex: 'customer_name'
        },
        {
            title: '地址',
            dataIndex: 'customer_address'
        },
        {
            title: '联系电话',
            dataIndex: 'customer_phone'
        },
        {
            title: '微信昵称',
            dataIndex: 'customer_nickname'
        },
        {
            title: '线路名称',
            dataIndex: 'route_name'
        },
        {
            title: '优先级',
            dataIndex: 'customer_sort'
        },
        {
            title: '停靠位置',
            dataIndex: 'customer_position'
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                    <span style={{color: '#1890ff', cursor: 'pointer'}}
                          onClick={() => this.setModal2Visible(true, data)}>修改地址</span>
                    <EditCustomerPositions data={data} handleRefresh={() => this.handleGetCustomerAfterEdit()}/>
                        {
                            data.customer_nickname != null ?
                                <span style={{color: '#1890ff', cursor: 'pointer', marginLeft: 10}}
                                      onClick={() => this.handleUnBind(data.customer_id)}
                                >解绑</span> : ''
                        }
                    </span>
                )
            }
        }
    ];

    render() {
        return (
            <div>
                <div>
                    <Row>
                        <SearchLists
                            clickSearch={(value) => {
                                this.handleGetSearch(value)
                            }}
                            handleReset={() => {
                                this.handleReset()
                            }}
                        >
                        </SearchLists>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <Button type="primary"
                                    onClick={() => this.handleRefresh()}
                            >
                                刷新
                            </Button>
                        </Col>
                    </Row>
                    <Row style={{marginTop: '20px'}}>
                        <Col span={24}>
                            <Table
                                columns={this.columns}
                                rowKey={record => record.customer_id}
                                dataSource={this.state.data}
                                pagination={false}
                                loading={this.state.loading}
                            />
                        </Col>
                    </Row>
                    <Row style={{marginTop: '20px'}}>
                        <Col span={12} style={{fontSize: '15px'}}>
                            共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current} / {this.state.allPage}
                            页
                        </Col>
                        <Col span={12} style={{textAlign: 'right'}}>
                            <Pagination {...this.state.pagination} showSizeChanger={true} showQuickJumper={true}
                                        onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}
                                        onShowSizeChange={(current, size) => this.handleSizeChange(current, size)}
                                        hideOnSinglePage={false}/>
                        </Col>
                    </Row>
                </div>
                <div>
                    <Modal
                        maskClosable={true}
                        confirmLoading={this.state.editConfirmLoading}
                        title={'请输入'}
                        wrapClassName="vertical-center-modal"
                        width={'1000px'}
                        visible={this.state.editVisible}
                        onCancel={() => this.setModal2Visible(false)}
                        footer={[
                            <Button key="back" type="default" onClick={() => this.setModal2Visible(false)}>取消</Button>,
                            <Button key="submit" type='primary' onClick={() => this.handleSubmit()}>确定</Button>
                        ]}
                    >
                        <Row>
                            <Col offset={1} span={22}>
                                <Row style={{marginTop: '20px'}}>
                                    <MapComponent getPoint={(values) => this.getPoint(values)}
                                                  locationData={this.state.locationData}/>
                                </Row>
                                <Row style={{marginTop: '20px'}}>
                                    <Col span={24}>地址：{this.state.locationData.address}</Col>
                                </Row>
                                <Row style={{marginTop: '15px'}}>
                                    <Col span={7}>经度：{this.state.locationData.longitude}</Col>
                                    <Col span={7}>纬度：{this.state.locationData.latitude}</Col>
                                </Row>
                                <Row style={{marginTop: '15px'}}>
                                    <Col span={7}><Input placeholder="请输入路线名" value={this.state.routeName}
                                                         onChange={(e) => this.handleChangeRouteName(e)}/></Col>
                                    <Col span={7}><Button type="primary" style={{marginLeft: '10px'}}
                                                          onClick={() => this.handleSearchRoute()}>搜索</Button></Col>
                                </Row>
                                <Row style={{marginTop: '15px'}}>
                                    <Col span={7}>
                                        <Select placeholder="请选择路线" style={{width: '100%'}} id="route_id"
                                                onChange={this.handleOnChangeRouteName} value={this.state.route_id}>
                                            {
                                                this.state.routeItem.map((item, index) => {
                                                    return (
                                                        <Option key={index}
                                                                value={item.route_id}>{item.route_name}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    </Col>
                                    <Col offset={11} span={6}>
                                        <Col span={10} style={{height: '32px', lineHeight: '32px'}}>优先级:</Col>
                                        <Col span={14}>
                                            <FormItem validateStatus={this.state.validateStatus}
                                                      help={this.state.helpStr}>
                                                <Input placeholder="请输入" value={this.state.customer_sort}
                                                       onChange={(e) => this.handleChangeSort(e)}
                                                       id="customer_sort"/>
                                            </FormItem>
                                        </Col>
                                    </Col>
                                </Row>
                            </Col>
                        </Row>
                    </Modal>
                </div>
            </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "客户管理"});
        this.handleGetCustomerList();
        this.handleGetRouteItem();
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        }
    };

    /**
     * 获取输入框值调用方法查询路线列表
     */
    handleSearchRoute() {
        const routeName = this.state.routeName;
        this.handleGetRouteItem(routeName);
    }

    /**
     * 查询路线列表事件
     * @param route_name
     */
    handleGetRouteItem(route_name) {
        let data = {
            page: 1,
            size: 10,
            route_name: route_name
        };
        app.post(line.SEARCH_LINE_LIST, data).then((result) => {
            if (result.code === 1) {
                this.setState({
                    routeItem: result.data.dataSet
                })
            } else {
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 处理路线选择变化事件
     * @param value
     */
    handleOnChangeRouteName = (value) => {
        this.setState({route_id: value});
    };
    /**
     * 处理优先级输入框事件
     * @param e
     */
    handleChangeSort = (e) => {
        let value = e.target.value;
        if (value.length <= 0) {
            this.setState({validateStatus: '', helpStr: ''});
            this.setState({customer_sort: ''});
            return;
        }
        let result = app.checkIsNum(value);
        if (!result) {
            this.setState({validateStatus: 'error', helpStr: '请输入正数'});
            return;
        } else {
            this.setState({validateStatus: '', helpStr: ''});
        }
        this.setState({customer_sort: value});
    };

    /**
     * 处理搜索路线输入框事件
     * @param e
     */
    handleChangeRouteName = (e) => {
        this.setState({routeName: e.target.value});
    };

    /**
     * 处理搜索事件
     * @param value
     */
    handleGetSearch(value) {
        this.setState({
            searchData: {
                customer_name: value.customer_name,
                route_name: value.route_name,
                customer_code: value.customer_code,
                customer_phone: value.customer_phone,
                customer_nickname: value.customer_nickname
            }
        });
        let data = {
            page: 1,
            size: this.state.pagination.pageSize || 10,
            customer_name: value.customer_name,
            route_name: value.route_name,
            customer_code: value.customer_code,
            customer_phone: value.customer_phone,
            customer_nickname: value.customer_nickname
        };
        this.handleGetCustomerList(data);
    };

    /**
     * 处理刷新按钮事件
     */
    handleRefresh() {
        const _this = this;
        app.post(customer.UPDATE_CUSTOMER, {}).then((result) => {
            if (result.code === 1) {
                app.alert(result.msg, 'success', 3);
                _this.handleReset();
            } else {
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 处理修改客户信息弹框事件
     * @param visible
     * @param data
     */
    setModal2Visible(visible, data) {
        if (visible) {
            let locationData = {
                address: data.customer_address,
                latitude: data.customer_y,//纬度
                longitude: data.customer_x//经度
            };
            this.setState({
                editVisible: visible,
                editCustomerId: data.customer_id,
                route_id: data.route_id,
                customer_sort: data.customer_sort,
                locationData,
                customer_name: data.customer_name,
                customer_phone: data.customer_phone,
                customer_position: data.customer_position
            })
        }
        this.setState({editVisible: visible});
    };

    /**
     * 获取地址和经纬度事件
     * @param values
     */
    getPoint(values) {
        this.setState({
            locationData: values
        })
    };

    /**
     * 搜索客户列表事件
     * @param data
     */
    handleGetCustomerList(data = {page: 1, size: 10, customer_name: '', route_name: ''}) {
        this.setState({loading: true});
        app.post(customer.SEARCH_CUSTOMER, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                let customerData = result.data.dataSet;
                console.log(customerData);
                for (let i = 0; i < customerData.length; i++) {
                    customerData[i].x_y = customerData[i].customer_x + ' , ' + customerData[i].customer_y;
                }
                this.setState({
                    pagination,
                    loading: false,
                    data: customerData,
                    allPage
                })
            } else {
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                this.setState({loading: false, data: [], pagination, allPage});
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        this.handleGetCustomerList(data);
    };

    /**
     * 处理页码变化事件
     * @param current
     * @param size
     */
    handleSizeChange(current, size) {
        let data = this.state.searchData;
        data.page = current;
        data.size = size;
        this.handleGetCustomerList(data);
    };

    /**
     * 处理重置按钮事件
     */
    handleReset() {
        this.setState(({searchData: {}}));
        this.handleGetCustomerList();
    };

    /**
     * 处理提交修改事件
     */
    handleSubmit() {
        let customer_sort = this.state.customer_sort;
        let value = customer_sort;
        if (value == null || value == undefined || value.length <= 0) {
            this.setState({validateStatus: '', helpStr: ''});
        } else {
            let result = app.checkIsNum(value);
            if (!result) {
                this.setState({validateStatus: 'error', helpStr: '请输入正数'});
                return;
            }
        }
        let customer_id = this.state.editCustomerId;
        let customer_address = this.state.locationData.address;
        let route_id = this.state.route_id;
        let customer_x = this.state.locationData.longitude;
        let customer_y = this.state.locationData.latitude;
        let data = {
            customer_sort: customer_sort,
            customer_id: customer_id,
            customer_address: customer_address,
            route_id: route_id,
            customer_x: customer_x,
            customer_y: customer_y,
        };
        app.post(customer.EDIT_CUSTOMER, data).then((result) => {
            if (result.code === 1) {
                app.alert('修改成功', 'success', 3);
                this.handleGetCustomerAfterEdit();
                this.setState({editVisible: false});
            } else {
                app.alert(result.msg, 'error', 3);
            }
        })
    };

    /**
     * 更新操作后获取客户列表
     */
    handleGetCustomerAfterEdit() {
        let searchData = this.state.searchData;
        let pagination = this.state.pagination;
        searchData.page = pagination.current ? pagination.current : 1;
        searchData.size = pagination.size ? pagination.size : 10;
        this.handleGetCustomerList(searchData);
    };

    /**
     * 处理解绑微信事件
     * @param id
     */
    handleUnBind(id) {
        const _this = this;
        const data = {
            customer_id: id
        };
        confirm({
            title: '',
            content: '确认要解绑微信吗？',
            onOk() {
                app.post(customer.UNBIND_CUSTOMER, data).then((result) => {
                    if (result.code === 1) {
                        app.alert('解绑成功', 'success', 2);
                        _this.handleGetCustomerAfterEdit();
                    } else {
                        app.alert('解绑失败', 'error', 2);
                    }
                })
            },
            onCancel() {

            }
        })
    }
};

class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <Form className="login-form">
                        <Row>
                            <Col span={6}>
                                <FormItem label="客户编号" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('customer_code')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label="客户名" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('customer_name')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label="路线名" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('route_name')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={6} style={{float: 'right'}}>
                                <Button type="primary"
                                        onClick={() => this.handleSearchComplain()}
                                >
                                    查询
                                </Button>
                                <Button type="default"
                                        onClick={() => this.handleReset()}
                                        style={{marginLeft: '10px'}}
                                >
                                    重置
                                </Button>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={6}>
                                <FormItem label="联系电话" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('customer_phone')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label="微信昵称" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('customer_nickname')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Row>
            </div>
        )
    };

    componentDidMount() {

    };

    /**
     * 获取搜索条件
     */
    handleSearchComplain() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 重置按钮事件
     */
    handleReset() {
        this.props.form.resetFields();
        this.props.handleReset();
    };

    /**
     * 处理输入框按下回车键的事件
     */
    handleOnPressEnter() {
        //调用获取搜索条件的函数
        this.handleSearchComplain();
    };
};

const SearchLists = Form.create()(SearchList);
const CustomerManages = Form.create()(CustomerManage);
export default prop => (
    <Consumer>
        {
            props => (
                <CustomerManages {...prop} {...props}/>
            )
        }
    </Consumer>
);